package service

import (
	. "gameserver/server"
	"gameserver/server/redisutil"

	"gitee.com/night-tc/gobige/common"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/msgdef"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
	"gitee.com/night-tc/gobige/msghandler"
	"gitee.com/night-tc/gobige/sess"
	"gitee.com/night-tc/gobige/threads"
)

/*
管理客户端连接
*/
type ClientMgr struct {
	*sess.NetSrv
}

func NewClientMgr(thgo *threads.ThreadGo, info *global.ListenCfg, msgh *msghandler.MsgHandler) (result *ClientMgr) {
	result = new(ClientMgr)
	result.NetSrv = sess.NewNetServer(info, thgo, result,
		sess.NetSrvSetIsClient(true),
		sess.NetSrvSetMsgHander(msgh))
	return
}

// 连接被关闭的时候(这个回调会在任意协程上，所以需要注意安全)
func (this *ClientMgr) SessClosed(sessed sess.INetSess) {
	/*
		连接关闭的时候，需要做一个定时器，等一下卸载用户数据
	*/
	this.NetSrv.SessClosed(sessed)
}

/*
会话的验证回调

如果是连接客户端的上层需要重载实现验证逻辑，失败就返回错误，底层会关闭连接
*/
func (this *ClientMgr) SessVerify(msg msgdef.ISessionVerifyReqMsg, sessmd sess.INetSess) (result error) {
	/*
	   验证客户端的token然后再通过
	*/
	defer func() {
		if result != nil {
			sessmd.Send(&protomsg.ClientVerifyFailedRet{})
		}
	}()
	putil := redisutil.NewGateSession(msg.GetSessUID())
	info, err := putil.GetInfo(nil)
	if err != nil {
		return err
	}
	if info[redisutil.GateSession_Key_Token] != msg.GetToken() ||
		common.NewString(info[redisutil.GateSession_Key_Gateway]).ToUint64V() != global.GetCfgInst().GetServerID() {
		//验证失败
		return Err_SessVerify_Fail
	}
	return this.NetSrv.SessVerify(msg, sessmd)
}
